#include "CCefURLRequestClient.h"
#include "CCefHandler.h"

CCefURLRequestClient::CCefURLRequestClient(CefRefPtr<CefFrame> _frame) : _dataLength(0)
{
}

void CCefURLRequestClient::OnRequestComplete(CefRefPtr<CefURLRequest> request)
{
	std::string statusText = "Unknown";
	std::map<int, std::string> mqpReqStatus;
	mqpReqStatus[0] = "Unknown";
	mqpReqStatus[1] = "Success";
	mqpReqStatus[2] = "Pending";
	mqpReqStatus[3] = "Canceled";
	mqpReqStatus[4] = "Failed";

	if (mqpReqStatus.find(request->GetRequestStatus()) != mqpReqStatus.end())
		statusText = mqpReqStatus[request->GetRequestStatus()];

	_response = request->GetResponse();

	_data = _resourceHandler->_clientHandler->_OnResourceResponse( _resourceHandler->_browser, _resourceHandler->_frame,
		request->GetRequest(), request->GetRequestStatus(), request->GetRequestError(), request->GetResponse(),
		_data);

	_dataLength = _data.length();

	//ResourceHandler.GetResponseHeaders() will get called
	//after _responseHeadersReadyCallback.Continue() is called.
	_resourceHandler->_content = _data;
	_resourceHandler->_responseHeadersReadyCallback->Continue();
}

void CCefURLRequestClient::OnDownloadData(CefRefPtr<CefURLRequest> request, const void* data, size_t data_length)
{
	auto buf = new char[data_length + 1];
	if (buf != nullptr)
	{
		memset(buf, 0, data_length + 1);
		memcpy(buf, data, data_length);
		_data += buf;
		delete buf;
	}
}

